package com.heima.article.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApArticleSearch;
import com.heima.article.entity.ApArticleSearchRepository;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private IApArticleContentService apArticleContentService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOService minIOService;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @GetMapping("/html/{id}")
    public ResponseResult freemarker(@PathVariable Long id ) throws IOException, TemplateException {
        ApArticle article = apArticleService.getById(id);


        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getContent,article);
        ApArticleContent one = apArticleContentService.getOne(query);

        Template template = configuration.getTemplate("article.ftl");
        Map<String,Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(one.getContent()));
        StringWriter out = new StringWriter();
        template.process(map,out);

        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        String url = minIOService.upload(id + ".html", is, "text/html");
        article.setStaticUrl(url);
        apArticleService.updateById(article);

        return ResponseResult.okResult();


    }

    /**
     * es初始化数据
     * @return
     */
    @GetMapping("/index")
    public ResponseResult index(){
        restTemplate.createIndex(ApArticleSearch.class);
        return ResponseResult.okResult("初始化完成");
    }

    /**
     * es添加映射
     * @return
     */
    @GetMapping("/putmapping")
    public ResponseResult mapping(){
        restTemplate.putMapping(ApArticleSearch.class);
        return ResponseResult.okResult("列表创建成功");
    }

    /**
     * 添加数据
     * @return
     */
    @GetMapping("/addDoc")
    public ResponseResult addDoc(){
        List<ApArticle> list = apArticleService.list();
        for (ApArticle apArticle : list) {
            ApArticleSearch apArticleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,apArticleSearch);

            IndexQuery query = new IndexQuery();
            query.setId(apArticle.getId().toString());
            query.setObject(apArticleSearch);
            restTemplate.index(query);
        }
        return ResponseResult.okResult("完成");
    }

    /**
     * 接口仓库
     */
    @Autowired
    private ApArticleSearchRepository searchRepository;

    /**
     * 添加数据
     * @return
     */
    @GetMapping("/add")
    public ResponseResult add(){
        List<ApArticle> list = apArticleService.list();
        List<ApArticleSearch> searches = new ArrayList<>();
        for (ApArticle apArticle : list) {
            ApArticleSearch apArticleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,apArticleSearch);
            searches.add(apArticleSearch);
        }
        searchRepository.saveAll(searches);
        return ResponseResult.okResult();
    }

    /**
     * 根据id 删除数据
     * @param id
     * @return
     */
    @GetMapping("del/{id}")
    public ResponseResult del(@PathVariable Long id){
        searchRepository.deleteById(id);
        return ResponseResult.okResult();
    }

    /**
     * 根据id 添加数据
     * @param id
     * @return
     */
    @GetMapping("add/{id}")
    public ResponseResult addById(@PathVariable Long id){
        ApArticle apArticle = apArticleService.getById(id);
        if (apArticle != null){
            ApArticleSearch apArticleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,apArticleSearch);
            searchRepository.save(apArticleSearch);
        }
        return ResponseResult.okResult();
    }

    /**
     * 根据id 查询数据
     * @param id
     * @return
     */
    @GetMapping("/find/{id}")
    public ResponseResult findById(@PathVariable Long id){
        Optional<ApArticleSearch> apArticleSearch = searchRepository.findById(id);
        System.err.println(apArticleSearch);
        return ResponseResult.okResult();
    }

}
